﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Net;
using System.Threading;
using System.Configuration;
using Entities.Utilities;

namespace giftdeliveryservice.Utility
{
    public class EmailUtilitly
    {

        public const string MatchEmailPattern = @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
     + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
     + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
     + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
        
        #region Local Variables
        
        private string message = string.Empty;
        private string subject = string.Empty;
        private string smtpserver = string.Empty;
        private int port;
        private string username = string.Empty;
        private string password = string.Empty;
        private string from = string.Empty;
        private bool authenticationrequired = false;

        #endregion

        #region Events

        public delegate void SentMailHandler(bool bSent);
        public static event SentMailHandler SentMailMessageCompleted;

        #endregion

        #region Properties

        /// <summary>
        /// Message Body, Write only property
        /// </summary>
        public string MessageBody
        {
            set
            {
                this.message = value;
            }
        }

        /// <summary>
        /// Message Subject, Write only property
        /// </summary>
        public string Subject
        {
            set
            {
                this.subject = value;
            }
        }

        /// <summary>
        /// From E mail Address, Write only property
        /// </summary>
        public string FromEmailAddress
        {
            set
            {
                this.from = value;
            }
        }

        #endregion

        #region Constructor        

        /// <summary>
        /// Initiate mail server according to the config values,
        /// If authentication is required make sure username and password is also availble in the config file
        /// </summary>       
        public EmailUtilitly()
        {
            this.smtpserver = ConfigurationManager.AppSettings["SMTPSERVER"];
            this.port = Convert.ToInt32(ConfigurationManager.AppSettings["PORT"]);

            this.authenticationrequired = Convert.ToBoolean(ConfigurationManager.AppSettings["ISAUTHENTICATIONREQUIRED"]);
            if (authenticationrequired)
            {
                this.username = ConfigurationManager.AppSettings["SMTPUSERNAME"];
                this.password = ConfigurationManager.AppSettings["SMTPPASSWORD"];
            }           
        }

        #endregion

        #region Instance - Members

 /// <summary>
        /// Sends a mail message
        /// </summary>
        /// <param name="from">
        /// from, a valid e mail address
        /// </param>
        /// <param name="subject">
        /// Mail subject
        /// </param>
        /// <param name="body">
        /// Mail body
        /// </param>
        /// <param name="to">
        /// To, a valid mail address
        /// </param>
        /// <param name="cc">
        /// Cc, a valid mail address
        /// </param>
        /// <returns>
        /// true, if sucessfully sent
        /// </returns>
        public bool SendMail(string from, string subject, string body, string to, string cc)
        {
            SmtpClient c = null;

            try
            {
                MailMessage m = new MailMessage(from, to);

                m.IsBodyHtml = true;

                // Add cc
                if (!string.IsNullOrEmpty(cc))
                    m.CC.Add(cc);

                m.Subject = subject;

                m.Body = body;

                // Initialize client
                c = new SmtpClient(this.smtpserver, this.port);
                c.EnableSsl = false;
                // Authentication
                if (this.authenticationrequired)
                {
                    NetworkCredential nc = new NetworkCredential(this.username, this.password);
                    c.UseDefaultCredentials = false;
                    //c.EnableSsl = true;
                    c.Credentials = nc;
                }

                c.DeliveryMethod = SmtpDeliveryMethod.Network;
                c.Send(m);

                // Success
                Interlocked.CompareExchange(ref SentMailMessageCompleted, null, null);
                if (SentMailMessageCompleted != null)
                {
                    SentMailMessageCompleted(true);
                }
            }
            catch (Exception exception)
            {             
                Interlocked.CompareExchange(ref SentMailMessageCompleted, null, null);
                if (SentMailMessageCompleted != null)
                {
                    SentMailMessageCompleted(false);
                }
                Log lg = new Log();
                lg.LogEntry("Error in sending email. exception =" + exception);
                return false;
            }
            finally
            {
                // Clean up
                if (c != null)
                    c.Dispose();
            }

            return true;
        }

        #endregion

       /*
        * 
            EmailUtil e = new EmailUtil();

            return e.SendMail(
                ConfigurationManager.AppSettings["SENDMAILFROM"],
                ConfigurationManager.AppSettings["SENDMAILSUBJECT"],
                "Sender name: " + Request["epost"] + "\n" + "Sender e-mail: " + Request["epost3"] + "\n" + "Sender message: \n" + Request["txtMsg"],
                ConfigurationManager.AppSettings["SENDMAILTO"],
                null
                );
        */
    }
}